package com.ktjiaoyu.crm.redis;

import redis.clients.jedis.Jedis;

/**
 * redis工具类
 */
public class RedisUtil {

    /**
     * 设置key的有效期，单位S
     * @param key
     * @param exTime
     * @return
     */
    public static Long expire(String key,int exTime){
        Jedis jedis = null;
        Long result = null;
        try {
            //从连接池中获取jedis实例
            jedis = RedisPool.getJedis();
            //设置成功返回Jedis对象
            result = jedis.expire(key,exTime);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放资源
            RedisPool.closeConn(jedis);
        }
        return result;
    }

    /**
     * 设置Key-value同时设置有效期
     * @param key
     * @param value
     * @param exTime
     * @return
     */
    public static String setEx(String key,String value,int exTime){
        Jedis jedis = null;
        String result = null;
        try {
            //从连接池中获取jedis实例
            jedis = RedisPool.getJedis();
            //设置成功返回Jedis对象
            result = jedis.setex(key,exTime,value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放资源
            RedisPool.closeConn(jedis);
        }
        return result;
    }

    /**
     * 设置key-value
     * @param key
     * @param value
     * @return
     */
    public static String set(String key,String value){
        Jedis jedis = null;
        String result = null;

        try {
            jedis = RedisPool.getJedis();
            result = jedis.set(key,value);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        } finally {
            RedisPool.closeConn(jedis);
        }
        return result;
    }

    /**
     * 根据key获取value
     * @param key
     * @return
     */
    public static String get(String key){
        Jedis jedis = null;
        String result = null;

        try {
            jedis = RedisPool.getJedis();
            result = jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        } finally {
            RedisPool.closeConn(jedis);
        }
        return result;
    }

    /**
     * 根据key删除value
     * @param key
     * @return
     */
    public static Long del(String key){
        Jedis jedis = null;
        Long result = null;

        try {
            jedis = RedisPool.getJedis();
            result = jedis.del(key);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        } finally {
            RedisPool.closeConn(jedis);
        }
        return result;
    }

}
